package com.zahb.qadx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.CornerImageView;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.GlideImageLoader;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class UploadCertificateActivity extends BaseActivity {
    @BindView(R.id.tvSave)
    TextView tvSave;
    @BindView(R.id.rlTwo)
    RelativeLayout rlTwo;
    @BindView(R.id.ivOne)
    ImageView ivOne;
    @BindView(R.id.iv)
    CornerImageView iv;
    @BindView(R.id.ivTwo)
    ImageView ivTwo;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvDes)
    TextView tvDes;

    int type = 0;
    @BindView(R.id.ivDeleteOne)
    ImageView ivDeleteOne;
    @BindView(R.id.ivDeleteTwo)
    ImageView ivDeleteTwo;
    @BindView(R.id.ivAddOne)
    ImageView ivAddOne;
    @BindView(R.id.ivAddTwo)
    ImageView ivAddTwo;
    @BindView(R.id.tvDesTwo)
    TextView tvDesTwo;


    @Override
    protected int getLayout() {
        return R.layout.activity_upload_certificate;
    }

    @Override
    protected void initViews() {

        mUnbinder = ButterKnife.bind(this);


        type = getIntent().getIntExtra("type", 0);
        if (type == 0) {
            if(MyArchivesActivity.archive!=null && MyArchivesActivity.archive.getIdcardVO()!=null){
                idcard = MyArchivesActivity.archive.getIdcardVO().getIdCardFrontImg();
                idcardBack = MyArchivesActivity.archive.getIdcardVO().getIdCardBackImg();

                if(!TextUtils.isEmpty(idcard)){
                    ImageLoaderKt.loadImage(ivOne, idcard);
                    ivAddOne.setVisibility(View.INVISIBLE);
                    tvDes.setVisibility(View.INVISIBLE);
                }
                if(!TextUtils.isEmpty(idcardBack)){
                    ImageLoaderKt.loadImage(ivTwo, idcardBack);
                    ivAddTwo.setVisibility(View.INVISIBLE);
                    tvDesTwo.setVisibility(View.INVISIBLE);
                }


            }
        } else if (type == 1) {
            rlTwo.setVisibility(View.INVISIBLE);

            tvTitle.setText("学历证书");
            tvDes.setText("上传学历证书\n支持JPG、PNG、JPEG");


            if(MyArchivesActivity.archive!=null && MyArchivesActivity.archive.getEducationImgVO()!=null){
                education = MyArchivesActivity.archive.getEducationImgVO().getEducationImg();

                if(!TextUtils.isEmpty(education)){
                    ImageLoaderKt.loadImage(ivOne, education);
                    ivAddOne.setVisibility(View.INVISIBLE);
                    tvDes.setVisibility(View.INVISIBLE);
                }

                rlTwo.setVisibility(View.INVISIBLE);
                ivAddTwo.setVisibility(View.INVISIBLE);
                tvDesTwo.setVisibility(View.INVISIBLE);
            }
        } else if (type == 2) {
            idcard = getIntent().getStringExtra("data");
            idcardBack = getIntent().getStringExtra("datatwo");

            ImageLoaderKt.loadImage(ivOne, idcard);
            ImageLoaderKt.loadImage(ivTwo, idcardBack);

            tvSave.setVisibility(View.INVISIBLE);
            ivDeleteOne.setVisibility(View.INVISIBLE);
            ivDeleteTwo.setVisibility(View.INVISIBLE);

            ivAddOne.setVisibility(View.INVISIBLE);
            tvDes.setVisibility(View.INVISIBLE);

            ivAddTwo.setVisibility(View.INVISIBLE);
            tvDesTwo.setVisibility(View.INVISIBLE);

        } else if (type == 3) {
            education = getIntent().getStringExtra("data");

            ImageLoaderKt.loadImage(ivOne, education);

            tvSave.setVisibility(View.INVISIBLE);


            rlTwo.setVisibility(View.INVISIBLE);

            tvTitle.setText("学历证书");
            tvDes.setText("上传学历证书\n支持JPG、PNG、JPEG");

            ivDeleteOne.setVisibility(View.INVISIBLE);
            ivDeleteTwo.setVisibility(View.INVISIBLE);

            ivAddOne.setVisibility(View.INVISIBLE);
            tvDes.setVisibility(View.INVISIBLE);

            ivAddTwo.setVisibility(View.INVISIBLE);
            tvDesTwo.setVisibility(View.INVISIBLE);
        }

        ivOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type >= 2) {
                    return;
                }


                PictureSelector.create(UploadCertificateActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideImageLoader.createGlideEngine())
                        .isEnableCrop(true)
                        .withAspectRatio(16,10)
                        .isCompress(true)
                        .compressQuality(60) // 图片压缩后输出质量
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(type == 0 ? 110 : 112);
            }
        });

        ivTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type >= 2) {
                    return;
                }
                PictureSelector.create(UploadCertificateActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideImageLoader.createGlideEngine())
                        .isEnableCrop(true)
                        .withAspectRatio(16,10)
                        .isCompress(true)
                        .compressQuality(60) // 图片压缩后输出质量
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(111);
            }
        });

        ivDeleteOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ivOne.setImageDrawable(getResources().getDrawable(R.drawable.transparent));
                idcard = "";

                education="";

                ivAddOne.setVisibility(View.VISIBLE);
                tvDes.setVisibility(View.VISIBLE);
            }
        });

        ivDeleteTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ivTwo.setImageDrawable(getResources().getDrawable(R.drawable.transparent));
                idcardBack = "";

                ivAddTwo.setVisibility(View.VISIBLE);
                tvDesTwo.setVisibility(View.VISIBLE);
            }
        });



        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (rlTwo.getVisibility() == View.VISIBLE) {
                    if (TextUtils.isEmpty(idcard)) {
                        showBindToast("请上传身份证正面");
                        return;
                    }
                    if (TextUtils.isEmpty(idcardBack)) {
                        showBindToast("请上传身份证背面");
                        return;
                    }
                    if(isReq){
                        return;
                    }
                    isReq=true;

                    Map<String, Object> params = new HashMap<>();
                    params.put("idCardFrontImg", idcard);
                    params.put("idCardBackImg", idcardBack);

                  Gson mGson = new Gson();
                    String json = mGson.toJson(params);

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
                    addDisposable(RetrofitService.getNetService()
                            .archives_idcard(body)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(response -> {
                                isReq=false;
                                if (response.getStatusCode() == 200) {


                                    Intent intent = new Intent(UploadCertificateActivity.this, UploadCertificateActivity.class);
                                    intent.putExtra("type", 1);
                                    startActivity(intent);


                                } else {
                                    showBindToast(response.getErrorInfo());
                                }
                            }, throwable -> {
                                throwable.printStackTrace();
                                Tips.RequestError(getActivity());
                            }));

                } else {

                    if (TextUtils.isEmpty(education)) {
                        showBindToast("请上传学历证书");
                        return;
                    }
                    if(isReq){
                        return;
                    }
                    isReq=true;
                    Map<String, Object> params = new HashMap<>();
                    params.put("educationImg", education);

                    Gson mGson = new Gson();
                    String json = mGson.toJson(params);

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
                    addDisposable(RetrofitService.getNetService()
                            .educatioimg(body)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(response -> {
                                isReq=false;
                                if (response.getStatusCode() == 200) {
                                    Intent intent = new Intent(UploadCertificateActivity.this, WorkExperienceActivity.class);
                                    startActivity(intent);
                                } else {
                                    showBindToast(response.getErrorInfo());
                                }
                            }, throwable -> {
                                throwable.printStackTrace();
                                Tips.RequestError(getActivity());
                            }));
                }


            }
        });

        archives();
    }

    public void archives(){
        addDisposable(RetrofitService.getNetService()
                .archives()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        MyArchivesActivity.archive = response.getData();
                    }else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
    @Override
    protected int getTitleStringRes() {
        type = getIntent().getIntExtra("type", 0);
        if(type==0){
            return R.string.upload_idcard;
        }
        if(type==1){
            return R.string.upload_education;
        }
        if(type==2){
            return R.string.idcard;
        }
        if(type==3){
            return R.string.education;
        }
        return R.string.upload_certificate;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 110 || requestCode == 111 || requestCode == 112) {
                List<LocalMedia> images =
                        PictureSelector.obtainMultipleResult(data);
                if (images.size() > 0) {
                    String path = GlideImageLoader.getPath(images.get(0));
                    upload(path, requestCode);

                }
            }

        }
    }

    public String idcard = "";
    public String idcardBack = "";
    public String education = "";

    public void upload(String path, int requestCode) {
        if (TextUtils.isEmpty(path)) {
            Log.v("zzw", "路径为空");
            return;
        }
        File imgFile = new File(path);
        if (!imgFile.exists() || !imgFile.isFile()) {
            Log.v("zzw", "文件不存在");
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", imgFile.getName(), requestBody);
        addDisposable(RetrofitService.getNetService()
                .upload(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        if (requestCode == 110) {
                            idcard = response.getData();
                            ImageLoaderKt.loadImage(ivOne, response.getData());

                            ivAddOne.setVisibility(View.INVISIBLE);
                            tvDes.setVisibility(View.INVISIBLE);
                        }
                        if (requestCode == 111) {
                            idcardBack = response.getData();
                            ImageLoaderKt.loadImage(ivTwo, response.getData());

                            ivAddTwo.setVisibility(View.INVISIBLE);
                            tvDesTwo.setVisibility(View.INVISIBLE);
                        }
                        if (requestCode == 112) {
                            education = response.getData();
                            ImageLoaderKt.loadImage(ivOne, response.getData());

                            ivAddOne.setVisibility(View.INVISIBLE);
                            tvDes.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
    boolean isReq=false;


}
